window.onload = function () {
    // 点击上传
    const UplaodBtn = getDomById('uploadExcelBtn')
    // console.log('UplaodBtn ===> ', UplaodBtn)
    // 监听点击上传
    UplaodBtn.addEventListener('click', uploadExcelBtn)

    // 监听选择完文件
    const uploadExcelSuccess = getDomById('uploadExcel')
    uploadExcelSuccess.addEventListener('change', function (event) {
        const selectedFile = event.target.files[0];
        console.log('selectedFile ====> ', selectedFile)
        if (selectedFile) {
            // 文件已选择
            readWorkbookFromLocalFile(selectedFile, (data) => {
                const worksheet = data.Sheets[data.SheetNames[0]];
                const jsonData = window.XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                console.log('jsonData ===> ', jsonData)
                // 处理json数据后 交互给页面
                formatingData(jsonData)
            })
            // 在这里可以执行你需要的操作，如上传文件等
        }
    });
}

// 点击上传按钮
function uploadExcelBtn() {
    console.log('uploadExcelBtnuploadExcelBtnuploadExcelBtn')
    const Upload = getDomById('uploadExcel')
    Upload.click()
}

function getDomById(id) {
    return document.getElementById(id)
}

// 读取本地excel
// 读取本地excel文件
function readWorkbookFromLocalFile(file, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        var workbook = window.XLSX.read(data, { type: 'binary' });
        if (callback) callback(workbook);
    };
    reader.readAsBinaryString(file);
}

// 处理数据
function formatingData(dataSource) {
    var header = dataSource[0];
    var result = [];

    for (var i = 1; i < dataSource.length; i++) {
        if (dataSource[i].length === 0) {
            continue; // 跳过空数组
        }
        var obj = {};
        for (var j = 0; j < header.length; j++) {
            var value = dataSource[i][j] || '';
            obj[header[j]] = value;
        }
        result.push(obj);
    }

    console.log('result处理好的大数据 ===》 ', result);

    // 通信给页面 result
    toContent(result)
}

function toContent(dresult) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        let message = { info: '来自popup的信息', dresult }
        chrome.tabs.sendMessage(tabs[0].id, message, res => {
            console.log('popup=>content')
            console.log(res)
        })
    })
}